<script setup>
import { ref, onMounted } from "vue";
import api from '../api/supply.js';
import dayjs from 'dayjs';

// 页面数据
const pageData = ref({
  records: [],
  total: 0,
  size: 10,
  current: 1,
  pages: 1
});

// 搜索文本
const searchText = ref('');

// 对话框控制
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const deleteDialogVisible = ref(false);

// 表单对象
const addObj = ref({
  sname: '',
  scontact: '',
  stel: '',
  saddress: ''
});

const editObj = ref({
  sid: '',
  sname: '',
  scontact: '',
  stel: '',
  saddress: ''
});

const deleteObj = ref({
  sid: '',
  sname: ''
});

// 表单验证规则
const rules = ref({
  sname: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  scontact: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  stel: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/, message: '请输入正确的电话号码或手机号码', trigger: 'blur' }
  ],
  saddress: [
    { required: true, message: '请输入地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ]
});

// 生命周期钩子
onMounted(() => {
  getTableList();
});

// 获取表格数据
const getTableList = async () => {
  const params = {
    current: pageData.value.current,
    size: pageData.value.size,
    searchtext: searchText.value || ''
  };

  try {
    const result = await api.getSupplierPage(params);
    pageData.value = result;
  } catch (error) {
    console.error("获取供应商数据失败:", error);
  }
};

// 分页处理
const handleSizeChange = (size) => {
  pageData.value.size = size;
  pageData.value.current = 1;
  getTableList();
};

const handleCurrentChange = (current) => {
  pageData.value.current = current;
  getTableList();
};

// 搜索处理
const handleSearch = () => {
  pageData.value.current = 1;
  getTableList();
};

// 删除供应商
const handleDelete = (row) => {
  deleteObj.value = {
    sid: row.sid,
    sname: row.sname
  };
  deleteDialogVisible.value = true;
};

const confirmDelete = async () => {
  try {
    await api.deleteSupplier(deleteObj.value.sid);
    getTableList();
    deleteDialogVisible.value = false;
  } catch (error) {
    console.error("删除供应商失败:", error);
  }
};

// 编辑供应商
const handleEdit = (row) => {
  editDialogVisible.value = true;
  editObj.value = { ...row };
};

const handlerEditConfirm = async () => {
  try {
    await api.editSupplier(editObj.value);
    getTableList();
    editDialogVisible.value = false;
  } catch (error) {
    console.error("更新供应商失败:", error);
  }
};

// 新增供应商
const handlerAddConfirm = async () => {
  try {
    await api.addSupplier(addObj.value);
    getTableList();
    addDialogVisible.value = false;
    // 重置表单
    addObj.value = {
      sname: '',
      scontact: '',
      stel: '',
      saddress: ''
    };
  } catch (error) {
    console.error("添加供应商失败:", error);
  }
};

// 取消操作
const handlerAddCancel = () => {
  addDialogVisible.value = false;
  addObj.value = {
    sname: '',
    scontact: '',
    stel: '',
    saddress: ''
  };
};

const handlerEditCancel = () => {
  editDialogVisible.value = false;
};
</script>

<template>
  <div class="supplier-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">供应商管理</h2>
      <p class="page-subtitle">管理供应商基本信息</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="global-card operation-card">
      <el-row :gutter="20" align="middle">
        <el-col :span="6">
          <el-input
              v-model="searchText"
              placeholder="搜索供应商ID/名称"
              clearable
              @clear="handleSearch"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch" class="action-button">
            <el-icon><Search /></el-icon> 查询
          </el-button>
        </el-col>
        <el-col :span="4" :offset="10">
          <el-button type="success" @click="addDialogVisible = true" class="action-button new-supplier-button">
            <el-icon><Plus /></el-icon> 新增供应商
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 供应商表格 -->
    <div class="global-card data-card">
      <el-table :data="pageData.records" style="width: 100%" stripe>
        <el-table-column prop="sid" label="供应商ID" width="120" align="center" />
        <el-table-column prop="sname" label="供应商名称" width="200" align="center">
          <template #default="{ row }">
            <el-tag type="info" class="supplier-tag">{{ row.sname }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="scontact" label="联系人" width="150" align="center" />
        <el-table-column prop="stel" label="联系电话" width="160" align="center" />
        <el-table-column prop="saddress" label="地址" min-width="200" align="center" />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
                size="small"
                @click="handleEdit(row)"
                icon="Edit"
                class="edit-button"
            >编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(row)"
                icon="Delete"
                class="delete-button"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
            v-model:current-page="pageData.current"
            v-model:page-size="pageData.size"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="custom-pagination"
        />
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除供应商"
        width="400px"
        class="delete-dialog"
    >
      <div class="dialog-content">
        <el-icon class="dialog-icon" color="#F56C6C"><WarningFilled /></el-icon>
        <p>确定要删除供应商 <strong>{{ deleteObj.sname }}</strong> 吗？</p>
        <p class="warning-text">此操作不可恢复，请谨慎操作！</p>
      </div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false" class="cancel-button">取消</el-button>
        <el-button type="danger" @click="confirmDelete" class="confirm-delete-button">确认删除</el-button>
      </template>
    </el-dialog>

    <!-- 新增供应商对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增供应商" class="form-dialog">
      <div class="dialog-header">
        <el-icon><OfficeBuilding /></el-icon>
        <span>添加新供应商信息</span>
      </div>
      <el-form :model="addObj" :rules="rules" ref="addForm" label-width="100px" class="supplier-form">
        <el-form-item label="供应商名称" prop="sname">
          <el-input v-model="addObj.sname" autocomplete="off" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="scontact">
          <el-input v-model="addObj.scontact" autocomplete="off" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="stel">
          <el-input v-model="addObj.stel" autocomplete="off" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="地址" prop="saddress">
          <el-input
              v-model="addObj.saddress"
              type="textarea"
              :rows="3"
              autocomplete="off"
              placeholder="请输入详细地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handlerAddCancel" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="handlerAddConfirm" class="confirm-button">确认新增</el-button>
      </template>
    </el-dialog>

    <!-- 编辑供应商对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑供应商" class="form-dialog">
      <div class="dialog-header">
        <el-icon><Edit /></el-icon>
        <span>编辑供应商信息</span>
      </div>
      <el-form :model="editObj" :rules="rules" ref="editForm" label-width="100px" class="supplier-form">
        <el-form-item label="供应商ID">
          <el-input v-model="editObj.sid" disabled />
        </el-form-item>
        <el-form-item label="供应商名称" prop="sname">
          <el-input v-model="editObj.sname" autocomplete="off" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="scontact">
          <el-input v-model="editObj.scontact" autocomplete="off" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="stel">
          <el-input v-model="editObj.stel" autocomplete="off" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="地址" prop="saddress">
          <el-input
              v-model="editObj.saddress"
              type="textarea"
              :rows="3"
              autocomplete="off"
              placeholder="请输入详细地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handlerEditCancel" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="handlerEditConfirm" class="confirm-button">保存修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.supplier-management {
  padding: 20px;
  background-color: #f0f7ff;
  min-height: calc(100vh - 60px);
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #d1e5f9;
}

.page-title {
  color: #1a3b6d;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
}

.page-subtitle {
  color: #4a7bb9;
  font-size: 15px;
}

/* 卡片样式 */
.operation-card {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  background-color: #ffffff;
}

.data-card {
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  background-color: #ffffff;
}

/* 按钮样式 */
.action-button {
  padding: 8px 15px;
  font-weight: 500;
  transition: all 0.3s;
  border-radius: 8px;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.new-supplier-button {
  background: linear-gradient(135deg, #4a6fa5, #6a89cc);
  border: none;
  color: white;
}

.new-supplier-button:hover {
  background: linear-gradient(135deg, #3a5a8c, #5a79bc);
}

.edit-button {
  background-color: #e3f2fd;
  border-color: #90caf9;
  color: #1565c0;
}

.delete-button {
  background-color: #ffebee;
  border-color: #ffcdd2;
  color: #a3c8f0;
}

/* 标签样式 */
.supplier-tag {
  background-color: #e3f2fd;
  border-color: #bbdefb;
  color: #0d47a1;
}

/* 分页样式 */
.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.custom-pagination {
  background: white;
  padding: 10px 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 对话框样式 */
.delete-dialog {
  border-radius: 10px;
  background: linear-gradient(to bottom, #ffffff, #f8fbff);
}

.dialog-content {
  text-align: center;
  padding: 20px;
}

.dialog-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.warning-text {
  color: #e74c3c;
  font-size: 14px;
  margin-top: 10px;
}

.form-dialog {
  border-radius: 12px;
  background: linear-gradient(to bottom, #ffffff, #f8fbff);
}

.dialog-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e1ecf7;
}

.dialog-header .el-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #4a6fa5;
}

.dialog-header span {
  font-size: 18px;
  font-weight: 600;
  color: #1a3b6d;
}

.supplier-form {
  padding: 0 20px;
}

/* 按钮样式 */
.cancel-button {
  background-color: #f5f7fa;
  border-color: #e1ecf7;
  color: #5a7ea9;
}

.confirm-button {
  background: linear-gradient(135deg, #4a6fa5, #6a89cc);
  border: none;
  color: white;
}

.confirm-button:hover {
  background: linear-gradient(135deg, #3a5a8c, #5a79bc);
}

.confirm-delete-button {
  background: linear-gradient(135deg, #e53935, #d32f2f);
  border: none;
  color: white;
}

.confirm-delete-button:hover {
  background: linear-gradient(135deg, #d32f2f, #c62828);
}

/* 输入框样式 */
.search-icon {
  color: #4a6fa5;
  font-size: 18px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .operation-card .el-row .el-col {
    margin-bottom: 10px;
  }

  .operation-card .el-col:last-child {
    margin-bottom: 0;
  }

  .new-supplier-button {
    width: 100%;
  }

  .edit-button, .delete-button {
    margin-bottom: 5px;
    width: 100%;
  }

  .el-col:last-child {
    text-align: right;
  }
}
</style>